package com.richmond.util;

import com.richmond.data.TimeRecord;
import com.richmond.data.Workday;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * User: csavard
 * Date: 12-08-06
 * Time: 18:08
 */
public class TimeSheetParser {
	private static Logger logger = Logger.getLogger(TimeSheetParser.class);

	public static List<Workday> parse(InputStream in) throws IOException {
		List<Workday> retValue = new Vector<Workday>();

		Workbook wb = new HSSFWorkbook(in);
		FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
		for (int i = 0; i < 14; i++) {
			Sheet sheet = wb.getSheetAt(i);
			Workday workday = new Workday();
			workday.setName(sheet.getSheetName());

			Row row = sheet.getRow(6);
			Cell cell = row.getCell(1);
			if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
				CellValue value = evaluator.evaluate(cell);
				if (value.getCellType() == Cell.CELL_TYPE_NUMERIC) {
					Date javaDate = HSSFDateUtil.getJavaDate(value.getNumberValue());
					workday.setDate(javaDate);
				}
			}

			retValue.add(workday);

			logger.info("---------- Jour: " + workday.getDate());

			Collection<TimeRecord> timeRecords = new Vector<>();

			int rowindex = 11;
			boolean noMore = false;
			while (rowindex < sheet.getLastRowNum() && !noMore) {
				row = sheet.getRow(rowindex);
				if (row != null) {
					Cell workernoCell = row.getCell(0);
					if (workernoCell != null) {
						Long noWorker = ParserUtil.getLongValue(workernoCell, evaluator);
						String workerName = row.getCell(1).getStringCellValue();
						if (noWorker != null || (workerName != null && workerName.length() > 5)) {
							TimeRecord record = new TimeRecord();
							if (noWorker != null) {
								record.setWorkerNo(noWorker);
							}
							record.setName(workerName);
							record.setCode(ParserUtil.getStringValue(row.getCell(2), evaluator));
							record.setCodeDescription(ParserUtil.getStringValue(row.getCell(3), evaluator));
							Float bonus = ParserUtil.getFloatValue(row.getCell(4));
							if (bonus != null) {
								record.setBonus(bonus);
							}
							for (int j = 5; j < 15; j++) {
								Float regular = ParserUtil.getFloatValue(row.getCell(j));
								if (regular != null) {
									record.setRegular(record.getRegular() + regular);
								}
							}
							timeRecords.add(record);
							logger.info((rowindex + 1) + ". " + record);
						}
					} else {
						noMore = true;
					}
				}
				rowindex++;
			}

			if (timeRecords.size() > 0) {
				workday.setTimeRecords(timeRecords);
			}

		}
		return retValue;
	}


}
